package AnnularDoubleLists;

import java.util.Iterator;

public class MyAnnularDoubleList implements Iterable<Integer>{
    private final Node sentinel;
    private static class Node {
        public Node prev;
        public int value;
        public Node next;

        public Node(Node prev, int value, Node next) {
            this.prev = prev;
            this.value = value;
            this.next = next;
        }
    }

    public MyAnnularDoubleList() {
        sentinel = new Node(null,0,null);
        sentinel.prev = sentinel;
        sentinel.next = sentinel;
    }

    //头插节点
    public void addFirst(int value) {
        Node hand = sentinel;
        Node tail = sentinel.next;
        Node addNode = new Node(hand,value,tail);
        hand.next = addNode;
        tail.prev = addNode;
    }

    //尾插节点
    public void addLast(int value) {
        Node prev = sentinel.prev;
        Node next = sentinel;
        Node addNode = new Node(prev,value,next);
        prev.next = addNode;
        next.prev = addNode;

    }


    //头删节点
    public void removeFirst() {
        Node remove = sentinel.next;
        if (remove == sentinel) {
            throw new RuntimeException("删除失败！");
        }
        Node next = remove.next;
        sentinel.next = next;
        next.prev = sentinel;
    }

    //尾删节点
    public void removeLast() {
        Node remove = sentinel.prev;
        Node prev = remove.prev;
        prev.next = sentinel;
        sentinel.prev = prev;
    }

    //根据值来删除节点
    private Node findValue (int value) {
        for (Node p = sentinel.next; p != sentinel; p = p.next) {
            if (p.value == value) {
                return p;
            }
        }
        return null;
    }

    public void removeValue (int value) {
        Node remove = findValue(value);
        if (remove == null) {
            throw new RuntimeException("找不到该数据来删除相对应的节点");
        }
        Node prev = remove.prev;
        Node next = remove.next;
        prev.next = next;
        next.prev = prev;
    }

    //实现迭代器
    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            Node p = sentinel.next;
            @Override
            public boolean hasNext() {
                return p != sentinel;
            }

            @Override
            public Integer next() {
                int value = p.value;
                p = p.next;
                return value;
            }
        };
    }
}
